/**
 * Kernel Monkeys
 * Andrew Boguk
 * Sergiy Kulyk
 * Nicholas Swartzendruber
 */

/*
 * timer.c
 *
 *  Created on: May 15, 2011
 *      Author: Nicholas Swartzendruber
 */

#include <stdio.h>
#include <pthread.h>
#include "./timer.h"

/**
 * A main function for testing purposes. This is
 * because unit testing is difficult to do with
 * the timer.


int main() {
	timer t =timer_initialize(&test_print);
	t->ms = 50;
	timer_start(t);
	sleep(2);
	timer_stop(t);
	printf("STOP\n");
	sleep(2);
	printf("2sec after stop\n");
	printf("restarting...\n");
	timer_start(t);
	sleep(2);
	printf("Killing...");
	timer_kill(t);
	return;
}
*/

/**
 * Called to allocate memory for a timer. Timer will be
 * started on its own thread.
 * @param func_ptr The function to call on each interval.
 * @return A timer pointer that may executed in it's own thread.
 */
Timer timer_initialize(void (*func_ptr)) {
	Timer t = (Timer) malloc(sizeof(timer_str));
	t->ms = DEFAULT_MS;
	t->stop = FALSE;
	t->pause = TRUE;
	t->func_ptr = func_ptr;
	pthread_t pth;
	pthread_create(&pth, NULL, timer_thread_start, t);
	return t;
}

/**
 * Called to start the passed timer.
 * @return void
 */
void timer_start(Timer t) {
	t->pause = FALSE;
	return;
}

/**
 * Helper method for starting a time on
 * it's own thread/running it.
 * @return void
 */
void * timer_thread_start(Timer t) {
	//Keep looping. If we need to  pause
    //then just ignore function calls.
	while(t->stop == FALSE) {
		if(t->pause == FALSE) {
			(t->func_ptr)();
		}
		usleep(t->ms * 1000);
	}
	t->stop = FALSE;
	return;
}

/**
 * Called to pause the timer that has
 * been passed. It may be restarted
 * with start.
 * @return void
 */
void timer_stop(Timer t) {
	t->pause = TRUE;
	return;
}

/**
 * Called to kill the timer. This means it
 * can not be restarted.
 */
void timer_kill(Timer t) {
	t->stop = TRUE;
	return;
}

void test_print(){
	printf("This is a print from timer, replace with function call.\n");
}
